# _*_ coding:utf-8 _*_
# @Time  : 2022.06.20
# @Author: zizlee
import datetime
import json
import time
import pandas as pd
import requests
import urllib3
urllib3.disable_warnings()


# 节假日
HOLIDAYS = ['2022-01-03', '2022-01-31', '2022-02-01', '2022-02-02', '2022-02-03', '2022-02-04',
            '2022-04-04', '2022-04-05', '2022-05-02', '2022-05-03', '2022-05-04', '2022-06-03',
            '2022-09-12', '2022-10-03', '2022-10-04', '2022-10-05', '2022-10-06', '2022-10-07']


# 进度打印
def print_progress_bar(current, total, color=35, title=''):  # percent是小数
    percent = round(current/total, 4)
    prefix_progress = '▓' * int(80 * percent)
    leave_progress = '▓' * (80 - int(80 * percent))
    # percent = '%.2f' % (percent * 100)
    print(f'\033[1;{color}m{current}/{total}\033[0m|\033[1;{color}m{prefix_progress}\033[0m{leave_progress} {title}')


def get_receipt(start_date=None, end_date=None, variety=None):
    if not start_date:
        start_date = datetime.datetime.today().strftime('%Y%m%d')
    if not end_date:
        end_date = datetime.datetime.today().strftime('%Y%m%d')

    query = {
        'start': start_date,
        'end': end_date,
        'variety': variety
    }
    url = 'https://210.13.218.130:9000/v1/datan/receipt/'
    r = requests.get(url, params=query, verify=False)
    return r.json()['data']['receipt_data']


def generate_data_list(start, end):  # 生成日期序列(去掉周末，节假日)
    data_list = []
    start = datetime.datetime.strptime(start, '%Y%m%d')
    end = datetime.datetime.strptime(end, '%Y%m%d')
    while start <= end:
        s = start.strftime('%Y-%m-%d')
        if s not in HOLIDAYS and start.isoweekday() < 6:
            data_list.append(s)
        start += datetime.timedelta(days=1)
    return data_list


def handler(indexes, start_date, end_date=None):
    total_count = len(indexes)
    if not start_date:
        start_date = datetime.datetime.today().strftime('%Y%m%d')
    if not end_date:
        end_date = datetime.datetime.today().strftime('%Y%m%d')
    receipt_data = get_receipt(start_date=start_date, end_date=end_date)

    df = pd.DataFrame(receipt_data)
    if df.empty:
        print(f'还没有{start_date}的仓单数据！')
        return
    date_list = generate_data_list(start=start_date, end=end_date)
    date_df = pd.DataFrame(date_list, columns=['datadate'])
    for i, index_item in enumerate(indexes):
        variety_en = index_item['variety_en']
        new_value_df = df[df['variety_en'] == variety_en][['receipt_date', 'receipt']]
        # 重命名类
        save_df = new_value_df.rename(columns={'receipt_date': 'datadate', 'receipt': 'datavalue'})
        # 处理数据
        save_df = pd.merge(date_df, save_df, on='datadate', how='left')
        save_df.fillna(0, inplace=True)
        if save_df.empty:
            print(f'今日无{index_item["name_zh"]}仓单数据!')
            continue
        save_data_to_server(index_item["id"], save_df.to_dict(orient='records'))
        msg = f'{index_item["source_id"]}:{index_item["name_zh"]},起始日期:{start_date}保存完成.'
        print_progress_bar(current=i + 1, total=total_count, color=35, title=msg)
        time.sleep(1)


# 保存数据到指标中
def save_data_to_server(sheet_id, datalist):
    url = 'https://210.13.218.130:9000/v1/datalib/table/update/'
    body_data = {'dataid': sheet_id, 'row_value': datalist}
    requests.post(url, json=body_data, verify=False)
    # print(r.json())


# 获取品种仓单数据
def get_variety_sum_receipt(start_date, variety_en):
    url = 'https://210.13.218.130:9000/v1/datan/receipt/totalReceipt/'
    r = requests.get(url, params={'start_date': start_date, 'v': variety_en}, verify=False)
    return r.json()['data']['data_list']


# 获取仓单数据的起始日期
def get_variety_receipt_start(variety_en, start_date = None):
    url = 'https://210.13.218.130:9000/v1/datan/receipt/startDate/'
    if start_date:
        ts = int(datetime.datetime.strptime(start_date, '%Y-%m-%d').timestamp())
    else:
        ts = None
    r = requests.get(url, params={'ts': ts, 'v': variety_en}, verify=False)
    print(r.json())


# 获取数据的起始日期
def get_server_index_start_date(iid: int):
    url = 'https://210.13.218.130:9000/v1/datalib/table/info/?iid=7436&page=1&page_size=2'
    r = requests.get(url, params={'iid': iid, 'page': 1, 'page_size': 10}, verify=False)
    index_info = r.json()['data']['index_info']
    s_date = index_info['startdate']
    e_date = index_info['enddate']
    return max([s_date, e_date]) if e_date else s_date


def handler_gfex(config_list):
    total_count = len(config_list)
    for j, row in enumerate(config_list, 1):
        start_date = get_server_index_start_date(iid=row['id'])
        new_data = get_variety_sum_receipt(start_date=start_date, variety_en=row['variety_en'])
        save_data = [{'datadate': i['receipt_date'], 'datavalue': i['t_receipt']} for i in new_data]
        save_data_to_server(row["id"], datalist=save_data)
        msg = f'{row["source_id"]}:{row["name_zh"]},起始日期:{start_date}保存完成.'
        print_progress_bar(current=j, total=total_count, color=35, title=msg)
        time.sleep(1)


def main(pointers=None):
    with open('R_品种仓单数量.json', encoding='utf8', mode='r') as fp:
        indexes = json.load(fp)
    print('读取数量:', len(indexes))
    if exchange:
        indexes = list(filter(lambda x: x['ex_code'] == exchange, indexes))
        # for i in indexes:
        #     # print("update all_ruizy_sheet set startdate='2022-01-04',enddate=NULL where id={};".format(i['id']))
        #     # print('truncate table rj_{};'.format(i['source_id']))
        #     print('delete FROM rj_{} where datadate=="2023-04-05";'.format(i['source_id']))
        # return
    if pointers:
        indexes = list(filter(lambda x: x['source_id'] in pointers, indexes))
    handler_indexes = list(filter(lambda x: x['ex_code'] != 'GFE', indexes))
    gfe_indexes = list(filter(lambda x: x['ex_code'] == 'GFE', indexes))
    print('待更新数量：', len(handler_indexes) + len(gfe_indexes))
    handler(indexes=handler_indexes, start_date=START, end_date=END)
    handler_gfex(config_list=gfe_indexes)


if __name__ == '__main__':
    START = ''
    END = ''
    exchange = ''
    main()
